package com.hw.paltfrom.service.system;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import com.hw.paltfrom.rescode.HWSystemCode;
import com.hw.paltfrom.utils.RandomNumberUtil;
import com.hw.paltfrom.utils.ResponeResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.hw.paltfrom.mapper.HwBaseAuthorizeMapper;
import com.hw.paltfrom.mapper.HwBaseModuleMapper;
import com.hw.paltfrom.pojo.HwBaseAuthorize;
import com.hw.paltfrom.pojo.HwBaseModule;
import com.hw.paltfrom.vo.BaseAuthorizeVo;

@Service
public class BaseAuthorizeServer {
	
	@Autowired
	private HwBaseAuthorizeMapper authorizeMapper;
	@Autowired
	private HwBaseModuleMapper baseModuleMapper;

	//增加,修改角色权限
	public Map<String, Object> insert(BaseAuthorizeVo vo) {
		//根据角色id删除旧权限
		EntityWrapper<HwBaseAuthorize> wrapper = new EntityWrapper<>();
		wrapper.eq("F_RoleId",vo.getfRoleid());
		authorizeMapper.delete(wrapper);
		//创建pojo对象
		HwBaseAuthorize hwBaseAuthorize = new HwBaseAuthorize();
		String createuserid = vo.getfCreateuserid();
		String createusername = vo.getfCreateusername();
		hwBaseAuthorize.setfRoleid(vo.getfRoleid());
		//循环添加权限
		
//		父类id
		HashSet<String> hashSet = new HashSet<String>();
		for(String objectid : vo.getfObjectids()){
			HwBaseModule byId = baseModuleMapper.selectById(objectid);
			String parentid = byId.getfParentid();
			hashSet.add(parentid);
		}
		hashSet.addAll( vo.getfObjectids());
		for (String objectid :hashSet) {
			hwBaseAuthorize.setfAuthorizeid(RandomNumberUtil.getNumber());
			hwBaseAuthorize.setfCreatedate(new Date());
			hwBaseAuthorize.setfCreateuserid(createuserid);
			hwBaseAuthorize.setfCreateusername(createusername);
			hwBaseAuthorize.setfObjectid(objectid);
//			hwBaseAuthorize.setfItemid(); 本项目默认为空
			hwBaseAuthorize.setfItemtype(1);//本项目默认为1
			hwBaseAuthorize.setfObjecttype(1);//本项目默认为1
			Integer insert = authorizeMapper.insert(hwBaseAuthorize);
			if (insert != 1){
				return ResponeResultUtil.failNotice(HWSystemCode.FAIL,"添加权限失败");
			}
		}

		return ResponeResultUtil.success(HWSystemCode.SUCCESS);
		
	}
	
	public Map<String, Object> queryAllList(String fRoleid) {
		//根据fRoleid查询所有权限
		Wrapper<HwBaseAuthorize> namewrapper = new EntityWrapper<HwBaseAuthorize>();
		namewrapper.eq("F_RoleId",fRoleid);
		List<HwBaseAuthorize> list = authorizeMapper.selectList(namewrapper);
		return ResponeResultUtil.successNotice(HWSystemCode.SUCCESS,list);
	}
}
